package com.zlm.pool;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 郑
 *线程池的四种拒绝策略
 * new ThreadPoolExecutor.AbortPolicy() 线程池队列也满了，不处理，抛出异常
 * new ThreadPoolExecutor.CallerRunsPolicy() 哪来的去哪里，不抛异常
 * new ThreadPoolExecutor.DiscardPolicy() 丢掉任务，不抛异常
 * new ThreadPoolExecutor.DiscardOldPolicy() 尝试和最早的竞争，不抛异常
 * 最大线程数如何定义
 * 1 CPU密集型  几核就是几
 * 2 IO密集型   核数的二倍
 *
 *
 * 线程池学习 ： 三大方法 七大参数 四大拒绝策略
 */
public class Demo2 {
    public static void main(String[] args) {
        //获取服务器核数
        int num = Runtime.getRuntime().availableProcessors();
        ThreadPoolExecutor pool = new ThreadPoolExecutor(2,//核心线程数
                num,//最大线程数
                5,//超时等待释放时间
                TimeUnit.SECONDS,//超时单位
                new LinkedBlockingDeque<>(3),//阻塞队列
                Executors.defaultThreadFactory(),//线程工厂
                new ThreadPoolExecutor.DiscardOldestPolicy());//拒绝策略
        try {
            for (int i = 0; i < 9; i++) {
                pool.execute(() ->{
                    System.out.println(Thread.currentThread().getName() + "ok");

                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭线程池
            pool.shutdown();
        }

    }
}

